package com.sky.aop;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAop {
   @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}

    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint){
       log.info("开始进行数据填充");
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = autoFill.value();
        Object[] args = joinPoint.getArgs();
        Long userId = BaseContext.getCurrentId();
        LocalDateTime  now = LocalDateTime.now();
        if (args != null && args.length > 0){
            Object arg = args[0];
            if (value == OperationType.INSERT){
                // 填充创建时间、更新时间
                try {
                    Method setUpdateTime = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                    Method setUpdateUser = arg.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                    Method setCreateTime = arg.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                    Method setCreateUser = arg.getClass().getDeclaredMethod("setCreateUser", Long.class);
                    setUpdateTime.invoke(arg, now);
                    setUpdateUser.invoke(arg, userId);
                    setCreateTime.invoke(arg, now);
                    setCreateUser.invoke(arg, userId);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            else if (value == OperationType.UPDATE){
                // 填充更新时间
                try {
                    Method setUpdateTime = arg.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                    Method setUpdateUser = arg.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                    setUpdateTime.invoke(arg, now);
                    setUpdateUser.invoke(arg, userId);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            
        }
    }
}
